/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi
 
    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/
var lg; // loading gif image

var uf;//upload form

var locstr; // base loc value

var errlocstr; // errloc value


// process user events relating to uploading files
function uploadAction(event) {
    switch (this.id) {
    case 'upload-lnk':
    		
	
	if (uf.is(':visible'))
	    uf.hide();
	else
	    uf.show();
	break;
    case 'upload-submit':
	getUploadUrl();
	break;
    case 'upload-cancel':
	cancelUpload();
	break;
    }
}

function checkLogout(data) {
    // didn't get an upload url. check if user was logged out
    if (data.indexOf("login",0) >= 0) {
	window.location.reload(true); // force the login page
	return;
    }
}

function beginUpload(data) {
    if ("http" != data.substring(0,4)) {
	checkLogout(data);
	cancelUpload();
	return;
    }
    
    lg.show();

    $('#upload-submit').attr("disabled", "disabled");

    // set the upload form's action and target, then submit.
    uf.attr("target", "upload-iframe");
    uf.attr("action", data);
    uf.submit();
}

function getUploadUrl() {
    if ($('#upload-file-select').val() == '') {
	alert("Please select a file to upload.");
	return;
    }

    if($('#permit').val() == null) {
	alert("Please select a Permission Level");
	return;
    }
    
    //if category is not chosen then default to 'other' type
    if($('#category').val() == null) {
    	category_val = 'other';
     }
    else
    {
    	category_val = $('#category').val();
    }
    
    //if the file is not named then do not add the parameter to the url
    file_name_param = '';
    if($('#file_name').val() != null) {
    	file_name_param = "&file_name="+$('#file_name').val();
    }
    
    //if the file is associated with a course then create the parameter string
    course_param = '';
    if($('#course_id').val() != null) {
    	course_param = "&course_id="+$('#course_id').val();
    }

    $('#loc').attr("value", locstr + "&permit="+$('#permit').val()+ "&category="+category_val+ file_name_param+course_param);
    $('#errloc').attr("value",errlocstr + "&permit="+$('#permit').val()+ "&category="+category_val+ file_name_param+course_param);

    lg.show();
    $.get("/files/getuploadurl", '', beginUpload, 'text');
}

function cancelUpload() {
    $('#upload-submit').removeAttr("disabled");
    $('#upload-iframe').attr("src","about:blank");
    $('#loc').attr("value",locstr);
    $('#errloc').attr("value",errlocstr);
    lg.hide();
    uf.hide();
    clearForm(uf);
}

function uploadDone() {
    $('#upload-submit').removeAttr("disabled");
    $('#loc').attr("value",locstr);
    $('#errloc').attr("value",errlocstr);
    lg.hide();
    uf.hide();
    clearForm(uf);
    reloadFilesList();
}

function displayFiles(data) {
    $('#files-list').html(data);
    setupDeleteLinks();
}

function deleteDocument() {
    if (confirm("Do you wish to delete \"" + $(this).attr("fc_doc") + "\"?" + "\nClick 'OK' to delete.")) {
	$.get("/files/delete?d=" + $(this).attr("fc_d") + "&c=" + $(this).attr("fc_c"),
	      '',
	      function (p) {
		  if ("OK" != p.substring(0,2)) {
		      alert("Sorry, could not delete this file.");
		  }
		  else {
		      reloadFilesList();
		  }
	      }, 'text');
    }
}

function setupDeleteLinks() {
    $('.delete-doc-lnk').click(deleteDocument);
}

function clearForm(form) {
    $(':input', form).each(function() {
	    var type = this.type;
	    var tag = this.tagName.toLowerCase(); // normalize case
	    if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'file')
		this.value = "";
	    else if (type == 'checkbox' || type == 'radio')
		this.checked = false;
	    else if (tag == 'select')
		this.selectedIndex = -1;
	});
}

$(document).ready(function(){
	$('#upload-lnk').click(uploadAction);
	$('#upload-cancel').click(uploadAction);
	$('#upload-submit').removeAttr("disabled");
	$('#upload-submit').click(uploadAction);
	setupDeleteLinks();
	lg = $('#loader-gif');
	locstr = $('#loc').val();
	errlocstr = $('#errloc').val();
	
	//some css is dependent on the for id
	// and since different views use different css refs we need to find out what upload form ref to use
	uf = $(uploadFormRef());
	
	if ($('#upload-iframe').length == 0) {
	    // create the hidden iframe
	    uf.append("<iframe onload='uploadDone();' name='upload-iframe' id='upload-iframe' style='height:0px; width:0px; border:0px; display:none;' />");
	}
    });
